<template>
  <div id="barChart" style="width: 600px;height:400px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'BarChartComponent',
  data() {
    return {
      categories: [], // 类别名称列表
      seriesData: [], // 包含交易数据的对象数组
      billTypes: [], // 账单类型列表
    };
  },
  computed: {
    barChartData() {
      // 使用Map来统计每个类别的总金额
      const categoryTotals = new Map();

      this.seriesData.forEach(item => {
        const typeName = this.billTypes.find(type => type.typeId === item.typeId)?.name;
        if (typeName) {
          categoryTotals.set(typeName, (categoryTotals.get(typeName) || 0) + item.money);
        }
      });

      // 将Map转换为数组，以匹配categories的顺序
      return this.categories.map(category => categoryTotals.get(category.name) || 0);
    },
  },
  mounted() {
    this.loadData().then(() => {
      this.initChart();
    }).catch((error) => {
      console.error('Error loading data:', error);
    });
  },
  methods: {
    async loadData() {
      try {
        const [billInfoResponse, billTypeResponse] = await Promise.all([
          axios.get('https://youxuan-zua-api.tulan.wang/admin/ysf-bill-info/findPage?page=1&size=20'),
          axios.get('https://youxuan-zua-api.tulan.wang/admin/ysf-bill-type/page')
        ]);

        this.seriesData = billInfoResponse.data.data;
        this.billTypes = billTypeResponse.data.data;

        // 构建categories数组，其中包含所有类别信息
        this.categories = this.billTypes.map(type => ({
          typeId: type.typeId,
          name: type.name
        }));
      } catch (error) {
        throw new Error('Failed to load data.');
      }
    },
    initChart() {
      const myChart = echarts.init(document.getElementById('barChart'));
      const option = {
        title: {
          text: '交易类型金额分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.categories.map(category => category.name),
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '交易金额',
            type: 'bar',
            data: this.barChartData,
            barWidth: '60%',
            itemStyle: {
              color: '#5470C6'
            }
          }
        ]
      };

      myChart.setOption(option);
    },
  },
};
</script>